#!/usr/bin/python
# -*- coding: UTF-8 -*-

import json
import requests
import os
import sys
import py2curl
from datetime import datetime
from datetime import timedelta
import time as timeS
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

####################################################################################################
# 全局配置
url = "http://esrest.sinaops.intra.weibo.cn/maiops/getAggData.do"
url1 = "http://esrest.sinaops.intra.weibo.cn/maiops/getAggDataAuth.do"
headers = {
    "Content-Type": "application/json"
}
agent_os_type = {
    "adnroid": "android",
    "ios": "iphone"
}
#  数据模版
weibo_cache = {
    "android": {
        "range(0-500000000)": {
            "number": "",
            "percent": ""
        },
        "range(500000000-1000000000)": {
            "number": "",
            "percent": ""
        },
        "range(1000000000-2000000000)": {
            "number": "",
            "percent": ""
        },
        "range(2000000000-)": {
            "number": "",
            "percent": ""
        },
    }
}
####################################################################################################
# 微博缓存请求参数模版
cache_template = {
    "indexName": "logstash-webview-*",
    "timeFormat": "day",
    "timestamp": "",  # 2023-01-15-00-00~2023-01-16-00-00
    "fields": {
        "subtype": "cache_log",
        "log_type": "2",
        "agent_os_type": "",  # android 和iphone
        "query_string": "size_category.weibo:>=1000000000 AND size_category.weibo:<2000000000"  # 请查看缓存查询条件
    },
}
#  缓存查询条件
cache_query_string = {
    "range(0-500000000)": "size_category.weibo:>=0 AND size_category.weibo:<500000000",
    "range(500000000-1000000000)": "size_category.weibo:>=500000000 AND size_category.weibo:<1000000000",
    "range(1000000000-2000000000)": "size_category.weibo:>=1000000000 AND size_category.weibo:<2000000000",
    "range(2000000000-)": "size_category.weibo:>=2000000000",
}
####################################################################################################
#  慢速比
slow_speed_ratio_old_template = {
    "indexName": "logstash-mweibo-20*",
    "timeFormat": "day",
    "timestamp": "now-3d",  # 过去三天
    "fields": {
        "programname": "mweibo_client_performance_debug",
        "subtype": "image_loader_link_log",
        "agent_os_type": "android",
        "query_string": "waiting_time:>=1000"  # 查询条件
    },
}
slow_speed_ratio_query_imageloader = {
    "total": "waiting_time:>=0",
    "overtime": "waiting_time:>=1000"
}

slow_speed_ratio_new_template = {
    "indexName": "logstash-mweibo-20*",
    "timeFormat": "day",
    "timestamp": "now-3d",  # 过去三天
    "fields": {
        "programname": "mweibo_client_performance_debug",
        "subtype": "image_loader_link_log_glide",
        "agent_os_type": "android",
        "query_string": ""  # 查询条件
    },
}
slow_speed_ratio_query_glide = {
    "total": "*",
    "disk_cache": "is_request_successed_glide:1 AND load_complete_glide:DATA_DISK_CACHE AND waiting_time_glide:>=1000",
    "remote": "is_request_successed_glide:1 AND load_complete_glide:REMOTE AND local_request_glide:>=1000"

}

slow_speed_ratio_ios_template = {
    "indexName": "logstash-mweibo-20*",
    "timeFormat": "day",
    "timestamp": "now-3d",  # 过去三天
    "fields": {
        "programname": "mweibo_client_performance_debug",
        "subtype": "feed_image_show_link_log",
        "agent_os_type": "iphone",
        "query_string": ""  # 查询条件
    },
}
slow_speed_ratio_query_ios = {
    "total": "is_slow:*",
    "overtime": "is_slow:1"
}
####################################################################################################
# 白频率
username = "liangliang22@staff.weibo.com"
password = "WLL1992fg*"
#  session_id可能会过期，过期的话，自己通过账号访问看板抓包去获取吧。
SESSION_ID = "c6c4c388-bf01-491a-aa89-ce6fe6fa8948"

metabase_base_url = "http://dashboard.client.weibo.cn"
metabase_request_url = metabase_base_url + "/metabase/api/dashboard/129/dashcard/869/card/826/query"

metabase_android_parameters = {
    "parameters": [
        {"type": "date/all-options", "value": "past7days", "target": ["dimension", ["field", 6399, "null"]],
         "id": "83c8cafa"},
        {"type": "string/=", "value": ["android"], "target": ["dimension", ["field", 6403, "null"]],
         "id": "840b788d"}
    ],
    "dashboard_id": 129
}

metabase_ios_parameters = {
    "parameters": [
        {
            "type": "date/all-options", "value": "past7days", "target": ["dimension", ["field", 6399, "null"]],
            "id": "83c8cafa"},
        {"type": "string/=", "value": ["iphone"], "target": ["dimension", ["field", 6403, "null"]],
         "id": "840b788d"}
    ],
    "dashboard_id": 129
}
####################################################################################################
# 图片错误数据
pic_error_url = "http://sla.weibo.cn/php/start.php?api=ParamsTransferPic.getErrNoRatio&from=%s&to=%s&type=PicDownload&particle=day&systerm=%s&download_type=null"
pic_success_url = "http://sla.weibo.cn/php/start.php?api=ParamsTransferPic.getSuccRatio&from=%s&to=%s&type=PicDownload&particle=day&systerm=%s&download_type=null&download_type_in=true"

systerm = {
    "android": "ANDROID",
    "ios": "IPHONE"
}

####################################################################################################
# clientapm日志，筛选出uid
clientapm_template = {
    "size": 30000,
    "indexName": "logstash-clientapm-*",
    "timeFormat": "day",
    "timestamp": "now-1d",
    "agg_key": "uid",
    "fields": {
        "system": "iphone",
        "query_string": 'contents:*VTTileDecompressionSessionCreate* AND duration_range:">5s"'  # 查询条件
    },
}
####################################################################################################
# 微博占用大小
weibo_use_space_url = "http://sla.weibo.cn/php/start.php?api=ParamsTransferPic.getMemoryHitsTrend&from=%s&to=%s&type=client_memory&particle=day&&agent_os_type=%s&"
weibo_use_space_type = ["iphone", "android"]
####################################################################################################


def read_total_count(dict):
    return dict['hits']['total']


#  timestamp: 2021-08-19-00-00~2021-08-20-00-00
def get_lastday_range(type=1, days=1):
    now_time = datetime.now()
    if type == 1:
        lastday = (now_time + timedelta(days=-days)).strftime('%Y-%m-%d-00-00')
        today = now_time.strftime('%Y-%m-%d-00-00')
        timestamp = '%s~%s' % (lastday, today)
        return timestamp
    elif type == 2:
        lastday = (now_time + timedelta(days=-days)).strftime('%Y%m%d')
        return lastday


def query(url, headers, data):
    count = 0
    while count < 10:
        try:
            ret = requests.post(url, headers=headers, data=data)
            curlll = py2curl.render(ret.request)
            print(curlll)
            print(ret.text)
            reJson = ret.json()
            return reJson
        except Exception as e:
            count = count + 1
            print('错误 接口 ------> 重试次数 = %d' % count, e)
            timeS.sleep(2)
    else:
        raise AssertionError()


def query2(url, headers, data, request_type):
    count = 0
    while count < 10:
        try:
            ret = requests.post(url, headers=headers, data=data)
            curlll = py2curl.render(ret.request)
            print("请求url: ", curlll)
            reJson = ret.json()
            if request_type == 1:
                data = reJson['data']['pieData']
            elif request_type == 2:
                data = reJson['data']['lineData']
            if len(data) > 0:
                print("请求数据成功：%s" % ret.text)
                return reJson
            else:
                print("尚未请求到成功失败数据----> 重试次数 = %d" % count)
                count = count + 1
        except Exception as e:
            count = count + 1
            print('错误 接口 ------> 重试次数 = %d' % count, e)
            timeS.sleep(2)
    else:
        raise AssertionError()


def query3(url, headers, data):
    count = 0
    while count < 10:
        try:
            ret = requests.post(url, headers=headers, data=data)
            curlll = py2curl.render(ret.request)
            print(curlll)
            print(ret.text)
            reJson = ret.json()
            print("reJson: ", reJson)
            if reJson['aggregations'] is not None:
                if reJson['aggregations']['count'] is not None:
                    data = reJson['aggregations']['count']['buckets']
            if len(data) > 0:
                print("请求数据成功：%s" % ret.text)
                return reJson
            else:
                print("尚未请求到成功失败数据----> 重试次数 = %d" % count)
                count = count + 1
                timeS.sleep(2)
        except Exception as e:
            count = count + 1
            print('错误 接口 ------> 重试次数 = %d' % count, e)
            timeS.sleep(2)

    return None


def query_show_ratio(template, timestamp, agent_os_type, query_string, size):
    if timestamp is not None:
        template['timestamp'] = timestamp
    if agent_os_type is not None:
        template['fields']['agent_os_type'] = agent_os_type
    if query_string is not None:
        template['fields']['query_string'] = query_string
    if size > 0:
        template['size'] = size
    data = json.dumps(template, ensure_ascii=False)
    ret = query(url=url, headers=headers, data=data)
    parse_data = None
    if ret is not None:
        parse_data = ret['aggregations']['count']['buckets']
    return parse_data


def self_adaption_query_return_size(template, threshold=5000, original_size=1, timestamp=None, agent_os_type=None,
                                    query_string=None):
    '''
    根据错误阈值和查询前多少的size来自适应查询实际大于阈值的量
    :param threshold:
    :param original_size:
    :param timestamp:
    :param agent_os_type:
    :param query_string:
    :return:
    '''
    except_size = 0
    last_error_number = 0
    count = 0
    while True:
        data = query_show_ratio(template=template, timestamp=timestamp, size=original_size,
                                agent_os_type=agent_os_type, query_string=query_string)
        if data is not None:
            if len(data) > 0:
                last_error_number = data[len(data) - 1]['doc_count']
                if last_error_number > threshold:
                    except_size += original_size
                else:
                    for i in range(len(data)):
                        if data[i]['doc_count'] >= threshold:
                            except_size = i
            original_size = except_size
            if last_error_number < threshold:
                print("期望查询的size：", except_size + 1)
                return data, except_size + 1
        else:
            print("获取数据失败，重试次数--->%s" % count)
            count = count + 1

        if count > 10:
            raise AssertionError("重试次数：%s,仍然失败，直接退出" % count)


def query_data_by_os(template, agent_os_type, query_string, timestamp=None):
    template['fields']['agent_os_type'] = agent_os_type
    if timestamp is not None:
        template['timestamp'] = timestamp
    result = {}
    for key, value in query_string.items():
        template['fields']['query_string'] = value
        data = json.dumps(template, ensure_ascii=False)
        print("缓存请求配置参数 ", data)
        try:
            ret = query(url=url, headers=headers, data=data)
            print("缓存接口返回", ret)
            total = read_total_count(ret)
            print('目标值 %s' % (total))
            result[key] = total
        except Exception as e:
            print(e)
            result[key] = 0

    return result


def format_percentage(numerator, total, percent='%.2f%%'):
    if total == 0.0:
        return "数据异常"
    p = 100 * numerator / total
    if p == 0.0:
        q = '0%'
    else:
        q = percent % p
    return q


def format_pic_error_code(dict):
    data = dict['data']['pieData']
    total = 0
    result = {}
    dict_data = {}
    for value in data:
        error_code = value[0]
        error_number = value[1]
        total += int(error_number)
        dict_data[error_code] = error_number
    data = sorted(dict_data.items(), key=lambda x: x[1], reverse=True)
    for key, value in data:
        result[key] = {"number": value, "percent": format_percentage(value, total, percent='%.4f%%')}
    return result


def format_pic_success(dict):
    part_data = dict['data']['partData']
    total_data = dict['data']['totalData']
    return format_percentage(part_data[0]['data'][0], total_data[0]['data'][0], percent='%.4f%%')


def calculate_data(dict):
    total = 0
    result = {}
    for key, value in dict.items():
        total += int(value)
    for key, value in dict.items():
        result[key] = {"number": value, "percent": format_percentage(int(value), total)}

    return result


def get_weibo_cache_pv_data():
    weibo_cache = {}
    # 微博缓存请求
    android = query_data_by_os(template=cache_template,
                               query_string=cache_query_string,
                               timestamp=get_lastday_range(type=1),
                               agent_os_type="android")
    weibo_cache["android"] = calculate_data(android)

    ios = query_data_by_os(template=cache_template,
                           query_string=cache_query_string,
                           timestamp=get_lastday_range(type=1),
                           agent_os_type="iphone")
    weibo_cache["ios"] = calculate_data(ios)

    print("微博缓存数据<<时间：%s>>" % get_lastday_range(type=1))
    print(weibo_cache)

    return weibo_cache


def get_weibo_cache_uv_data():
    weibo_cache = {}
    # 微博缓存请求
    android = query_data_by_os(template=cache_template,
                               query_string=cache_query_string,
                               timestamp=get_lastday_range(type=1),
                               agent_os_type="android")
    weibo_cache["android"] = calculate_data(android)

    ios = query_data_by_os(template=cache_template,
                           query_string=cache_query_string,
                           timestamp=get_lastday_range(type=1),
                           agent_os_type="iphone")
    weibo_cache["ios"] = calculate_data(ios)

    print("微博缓存数据<<时间：%s>>" % get_lastday_range(type=1))
    print(weibo_cache)

    return weibo_cache


def get_slow_speed_ratio(template, library, query_string, agent_os_type="android"):
    result = query_data_by_os(template=template,
                              agent_os_type=agent_os_type,
                              query_string=query_string)
    if library is None:
        print("慢速比-%s" % agent_os_type, result)
    else:
        print("慢速比-%s-图片库:%s" % (agent_os_type, library), result)
    return result


def get_slow_speed_ratios():
    # imageloader库慢速比
    imageloader = get_slow_speed_ratio(template=slow_speed_ratio_old_template, library="imageloader",
                                       query_string=slow_speed_ratio_query_imageloader, agent_os_type="android")
    # glide库慢速比
    glide = get_slow_speed_ratio(template=slow_speed_ratio_new_template, library="glide",
                                 query_string=slow_speed_ratio_query_glide, agent_os_type="android")
    glide = {
        "total": glide['total'],
        "overtime": glide['disk_cache'] + glide['remote']
    }
    # ios慢速比
    ios = get_slow_speed_ratio(template=slow_speed_ratio_ios_template, library=None,
                               query_string=slow_speed_ratio_query_ios, agent_os_type="iphone")
    result = {
        "android": {
            "imageloader": imageloader,
            "glide": glide
        },
        "ios": {
            "ios": ios
        }
    }
    print(result)
    return result


def get_pic_success_error():
    lastday = get_lastday_range(type=2)
    pic_dict = {}
    for key, value in systerm.items():
        pic_url = pic_error_url % (lastday, lastday, value)
        print("%s图片错误统计信息请求链接: %s" % (key, pic_url))
        ret = query2(url=pic_url, headers=headers, data=None, request_type=1)
        error_data = format_pic_error_code(dict=ret)
        pic_url = pic_success_url % (lastday, lastday, value)
        print("%s图片成功统计信息请求链接: %s" % (key, pic_url))
        ret = query2(url=pic_url, headers=headers, data=None, request_type=2)
        success_data = format_pic_success(dict=ret)
        pic_dict[key] = {"error": error_data, "success": success_data}

    print(pic_dict)
    return pic_dict


def get_request_data_by_metabase(url, metabase_parameters, session_id):
    headers['X-Metabase-Session'] = session_id
    data = json.dumps(metabase_parameters, ensure_ascii=False)
    return query(url=url, headers=headers, data=data)


def paser_show_ratio_data(ret):
    data = ret['data']['rows']
    sum_value = 0
    for temp in data:
        sum_value = sum_value + temp[1]
    return data, format_percentage(numerator=sum_value, total=len(data) * 100, percent='%.4f%%')


def get_show_ratio_by_metabase():
    session_id = str(os.environ.get('session_id'))
    if session_id is None or session_id == 'None':
        session_id = SESSION_ID
    print("构建参数session_id:", session_id)
    show_ratio_data = {}
    ret = get_request_data_by_metabase(url=metabase_request_url, metabase_parameters=metabase_android_parameters, session_id=session_id)
    data, mean_value = paser_show_ratio_data(ret=ret)
    show_ratio_data['android'] = {
        "data": data,
        "mean": mean_value
    }
    print("android段白频率数据：%s, 平均值：%s" % (data, str(mean_value)))
    ret = get_request_data_by_metabase(url=metabase_request_url, metabase_parameters=metabase_ios_parameters,
                                       session_id=session_id)
    data, mean_value = paser_show_ratio_data(ret=ret)
    show_ratio_data['ios'] = {
        "data": data,
        "mean": mean_value
    }
    print("ios段白频率数据：%s, 平均值：%s" % (data, str(mean_value)))
    return show_ratio_data


def get_weibo_use_space():
    lastday = get_lastday_range(type=2)
    weibo_use_space = {}
    for agent_os_type in weibo_use_space_type:
        weibo_use_url = weibo_use_space_url % (lastday, lastday, agent_os_type)
        print("weibo占用内存大小统计信息请求链接: %s" % weibo_use_url)
        ret = query2(url=weibo_use_url, headers=headers, data=None, request_type=2)
        ret_data = ret['data']['lineData']
        for data in ret_data:
            if str(data['name']) == 'weibo':
                weibo_use_space[agent_os_type] = data['data'][0]

    return weibo_use_space


def write_html_file(pic_success_error, slow_raite, weibo_cache, show_ratio, use_space):
    time = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')
    content = \
        "<html>\n" + \
        "        <head>\n" + \
        "            <meta charset=UTF-8>\n" + \
        "        </head>\n" + \
        "        <link rel=stylesheet type=text/css href=\"http://weiboota.sinaapp.com/css/mail.css\"/>" + \
        "        <body><br/><br/><br/>" + \
        "           <div class=commit_info><h1 align=center>图片日常数据统计(时间：" + str(time) + ")</h1> </div>\n" + \
        "           <div class=commit_info><h3 align=center>ios成功率: " + str(
            pic_success_error['ios']['success']) + "    Android成功率: " + str(
            pic_success_error['android']['success']) + " </h3> </div>\n" + \
        "           <div class=commit_info><h3 align=center>微博平均占用大小    ios: " + str(use_space['iphone']) + " MB" + "     Android: " + str(use_space['android']) + " MB" + " </h3> </div>\n"

    error_code_content = \
        "           <div class=commit_info><h2 align=center>图片双端成功率和错误码统计 </h2> </div>\n" + \
        "           <table border=1 width=40% cellpadding=2 cellspacing=1 align=center>\n" + \
        "               <tr>\n" + \
        "                   <th width=\"5%\" align=\"center\">双端类型</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">图片错误码</th>\n" + \
        "                   <th width=\"15%\" align=\"center\">错误数量</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">占比</th>\n" + \
        "               </tr>\n"

    weibo_cache_content = \
        "           <br/><br/><br/><div class=commit_info><h2 align=center>图片双端微博缓存统计(时间：" + str(
            time) + ") </h2> </div>\n" + \
        "           <table border=1 width=90% cellpadding=2 cellspacing=1 align=center>\n" + \
        "               <tr>\n" + \
        "                   <th width=\"10%\" align=\"center\" rowspan=\"2\">双端类型</th>\n" + \
        "                   <th width=\"20%\" align=\"center\" colspan=\"2\">range[0-500000000)</th>\n" + \
        "                   <th width=\"20%\" align=\"center\" colspan=\"2\">range[500000000-1000000000)</th>\n" + \
        "                   <th width=\"20%\" align=\"center\" colspan=\"2\">range[1000000000-2000000000)</th>\n" + \
        "                   <th width=\"20%\" align=\"center\" colspan=\"2\">range[2000000000-∞)</th>\n" + \
        "               </tr>\n" + \
        "               <tr>\n" + \
        "                   <td>数量</td> \n" + \
        "                   <td >占比</td>\n" + \
        "                   <td>数量</td>\n" + \
        "                   <td >占比</td>\n" + \
        "                   <td>数量</td>\n" + \
        "                   <td >占比</td>\n" + \
        "                   <td>数量</td>\n" + \
        "                   <td >占比</td>\n" + \
        "               </tr>\n"

    slow_speed_ratio_content = \
        "           <br/><br/><br/><div class=commit_info><h2 align=center>图片双端慢速比统计(时间：过去三天) </h2> </div>\n" + \
        "           <table border=1 width=50% cellpadding=2 cellspacing=1 align=center>\n" + \
        "               <tr>\n" + \
        "                   <th width=\"10%\" align=\"center\">双端类型</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">新老图片库</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">超时请求量</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">总请求量</th>\n" + \
        "                   <th width=\"10%\" align=\"center\">慢速比</th>\n" + \
        "               </tr>\n" + \
        "               "

    show_ratio_content = \
        "           <br/><br/><br/><div class=commit_info><h2 align=center>图片双端白频率统计(时间：" + str(
            time) + ") </h2> </div>\n" + \
        "           <table border=1 width=50% cellpadding=2 cellspacing=1 align=center>\n" + \
        "               <tr>\n" + \
        "                   <th width=\"20%\" align=\"center\">双端类型</th>\n" + \
        "                   <th width=\"20%\" align=\"center\">白屏率</th>\n" + \
        "               </tr>\n"

    content += show_ratio_content
    for data_type in show_ratio:
        show_ratio_data = show_ratio[data_type]['data']
        if len(show_ratio_data) == 7:
            content += "               <tr>\n" + \
                       "                   <td>" + str(data_type) + "</td> \n" + \
                       "                   <td >" + str(format_percentage(show_ratio_data[6][1], 1)) + "</td>\n" + \
                       "               </tr>\n"
        else:
            content += "               <tr>\n" + \
                       "                   <td>" + str(data_type) + "</td> \n" + \
                       "                   <td >" + str(format_percentage(show_ratio_data[len(show_ratio_data)-1][1], 1)) + "</td>\n" + \
                       "               </tr>\n"
    content += "           </table>\n"

    content += slow_speed_ratio_content
    for os_type in slow_raite:
        slow_data = slow_raite[os_type]
        print(slow_data)
        for library in slow_data:
            library_data = slow_data[library]
            content += "<tr><td width=\"10%\">" + str(os_type) + "</td><td width=\"10%\">" + str(
                library) + "</td><td width=\"10%\">" + str(library_data['overtime']) + "</td><td width=\"10%\">" + str(
                library_data['total']) + "</td><td width=\"10%\">" + str(
                format_percentage(library_data['overtime'], library_data['total'])) + "</td></tr>\n"
    content += "           </table>\n"

    content += weibo_cache_content
    for os_type in weibo_cache:
        cache_data = weibo_cache[os_type]
        content += "               <tr>\n"
        content += "                   <td width=\"10%\">" + str(os_type) + "</td>\n"
        for range_type in cache_data:
            range_data = cache_data[range_type]
            content += "                   <td width=\"10%\">" + str(range_data['number']) + "</td>\n"
            content += "                   <td width=\"10%\">" + str(range_data['percent']) + "</td>\n"
        content += "               </tr>\n"
    content += "           </table>\n"

    content += error_code_content
    for os_type in pic_success_error:
        error_data = pic_success_error[os_type]['error']
        print(error_data)
        for error_code in error_data:
            error_code_data = error_data[error_code]
            content += "               <tr><td width=\"5%\">" + str(
                os_type) + "</td><td width=\"10%\" style=\"word-break: break-word\">" + str(
                error_code) + "</td><td width=\"15%\">" + str(
                error_code_data['number']) + "</td><td width=\"10%\">" + str(
                error_code_data['percent']) + "</td></tr>\n"
    content += "           </table>\n"
    content += "</body></html>"
    print(content)
    return content


def get_clientapm_data():
    data = json.dumps(clientapm_template, ensure_ascii=False)
    dir_name, file_name = os.path.split(os.path.abspath(sys.argv[0]))

    ret = query(url=url, headers=headers, data=data)
    data = ret['aggregations']['count']['buckets']
    filename = dir_name + '/clientapm.txt'
    with open(filename, 'w') as file_object:
        for temp in data:
            uid = temp['key']
            if (len(uid) == 10):
                file_object.write(uid + "\n")

    return filename


def send_mail(content, filename):
    account = str(os.environ.get('account'))
    password = str(os.environ.get('password'))
    print("构建参数account:", account)
    print("构建参数password:", password)
    receivers = str(os.environ.get('receivers'))
    to_addrs = receivers.split(",")
    print("构建参数to_addrs:", to_addrs)
    message = MIMEMultipart()
    message['From'] = account
    message['To'] = receivers
    message['Subject'] = '图片日常监测数据--测试'

    # 构建clientapm正文
    # clientapm_content = """
    #     iphone端 clientapm日志中uid统计
    #     请查看附件
    #     """
    # message.attach(MIMEText(clientapm_content, 'plain', 'utf-8'))
    # attachment = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
    # attachment['Content-Type'] = 'application/octet-stream'
    # attachment['Content-Disposition'] = 'attachment;filename="clientapm.txt"'
    # message.attach(attachment)

    attachment = MIMEText(content, "html", 'utf-8')
    message.attach(attachment)

    smtpObj = smtplib.SMTP('mail.staff.sina.com.cn')
    smtpObj.login(account, password)
    smtpObj.sendmail(account, to_addrs, message.as_string())
    print("邮件发送成功")


def main_release():
    print("=================图片成功率和错误数据====================")
    pic_success_error = get_pic_success_error()
    #  微博缓存数据
    print("=================微博缓存(pv)数据====================")
    weibo_cache = get_weibo_cache_pv_data()
    print("=================微博缓存(uv)数据====================")
    weibo_cache = get_weibo_cache_uv_data()
    print("=================图片慢速比数据====================")
    slow_raite = get_slow_speed_ratios()
    print("=================微博白频率数据====================")
    show_data = get_show_ratio_by_metabase()
    print("=================clientapm中用户uid数据====================")
    filename = get_clientapm_data()
    print("=================weibo占用大小数据====================")
    weibo_use_space = get_weibo_use_space()
    print("=================发邮件====================")
    message = write_html_file(pic_success_error=pic_success_error, slow_raite=slow_raite, weibo_cache=weibo_cache, show_ratio=show_data, use_space=weibo_use_space)
    send_mail(content=message, filename=filename)


def main_debug():
    a = format_percentage(0.0303, 1, percent='%.2f%%')
    print(a)
    print("=================图片成功率和错误数据====================")
    get_weibo_use_space()


def main_debug1():
    a = format_percentage(0.0303, 1, percent='%.2f%%')
    print(a)
    print("=================缓存UV数据====================")
    get_weibo_use_space()


if __name__ == '__main__':
    main_debug1()
    # main_release()
    # sql = "select ul_hid,uid,count() from logstash-mweibo-20* where programname ='mweibo_client_performance_debug' " \
    #       "and ((is_request_successed = false and not cancel_duration :*) or cancel_duration > 2) " \
    #       "and uicode =10000001 " \
    #       "and agent_os_type = 'iphone' " \
    #       "and subtype ='image_load_thread_log' " \
    #       "and @timestamp between '2023-02-08T10:00:00' and '2023-02-08T15:30:00' " \
    #       "group by ul_hid,uid group by count() DESC"
    # url2 = "http://esrest.sinaops.intra.weibo.cn/mapiops/essql.do"
    # query(url=url2, headers=headers, data=json.dumps({"sql": sql}))
